import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * @Author: XXHH
 * @CreateTime: 2025-04-27
 */
class MyBlockingQueue{
    private String[] data;
    // 用来记录当前队列中的元素个数
    private int size;
    private int head;
    private int tail;
    public MyBlockingQueue(int capacity){
        data = new String[capacity];
    }
    // 入队列
    public void put(String elem) throws InterruptedException {
        synchronized (this){
            while (size > data.length){
                this.wait();
            }
            data[tail] = elem;
            tail++;
            if (tail == data.length) tail = 0;
            size++;
            this.notify();
        }
    }
    // 出队列
    public String take(){
        // 如果队列为0，那么就阻塞
        synchronized (this){
            while (size == 0) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            String elem = data[head];
            head++;
            if (head == data.length) head = 0;
            size--;
            this.notify();
            return elem;
        }
    }
}

public class Demo39 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue(10);
        // 生产者
        Thread producer = new Thread(()->{
            int n = 0;
            while (true){
                try {
                    queue.put(n+" ");
                    System.out.println("生产元素: "+n);
                    n++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"producer");
        // 消费者
        Thread customer = new Thread(()->{
            while (true){
                String n = queue.take();
                System.out.println("消费元素"+n);
            }
        },"customer");
        producer.start();
        customer.start();
    }
}
